package _2022.hot100._5_最长回文子串;

/**
 * @author： YHSimon
 * @date： 2022-03-27 15:11
 */
public class Solution {
    public boolean judge(String s, int start, int end) {
        int n = (end - start + 1) / 2;
        for (int i = 0; i < n; i++) {
            if (s.charAt(start + i) != s.charAt(end - i)) {
                return false;
            }
        }
        return true;
    }

    //暴力求解
    public String longestPalindrome(String s) {
        int maxLen = 0;
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                if (judge(s, i, j) && (j - i + 1) > maxLen) {
                    res = s.substring(i, j + 1);
                    maxLen = j - i + 1;
                }
            }
        }
        return res;
    }

    //暴力求解+优化
    public String longestPalindrome2(String s) {
        int maxLen = 1;
        String res = s.substring(0, 1);
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + maxLen - 1; j < s.length(); j++) {
                if (judge(s, i, j) && (j - i + 1) > maxLen) {
                    res = s.substring(i, j + 1);
                    maxLen = j - i + 1;
                }
            }
        }
        return res;
    }

    //动态规划  165ms
    public String longestPalindrome3(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }
        int maxLen = 1;
        int begin = 0;
        //dp[i][j] 表示s[i..j]是否是回文串
        boolean[][] dp = new boolean[len][len];
        for (int i = 0; i < len; i++) {
            dp[i][i] = true;
        }

        char[] charArray = s.toCharArray();
        //递推开始
        //注意：左下角先填
        for (int j = 1; j < len; j++) {
            //枚举左边界，左边界的上限设置可以宽松一些
            for (int i = 0; i < j; i++) {
                if (charArray[i] != charArray[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                //只要dp[i][L]==true成立，就表示子串s[i..L]是回文，此时记录回文长度和起始位置
                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.longestPalindrome2("babad"));
    }
}
